package cn.mason.echarts.controller;

import cn.mason.echarts.model.User;
import cn.mason.echarts.service.UserService;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.security.token.SSOToken;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    @Qualifier("UserService")
    private UserService userService;

    /**
     * 个人信息的展示，修改
     * 需要先获取登录状态的用户id,用其来从数据库拿到该数据所有信息再在页面展示
     * @return "myinfo"
     */
    @RequestMapping(value = "/myinfo",method = RequestMethod.GET)
    public String myinfo(HttpServletRequest request,Model model) {
        /*

         */
        String id = SSOHelper.getSSOToken(request).getId();
        User user = new User();
        user = userService.selectByPrimaryKey(id);
        logger.info("从数据库得到的数据是<<<<<<<<  "+user);
        model.addAttribute("user",user);
        return "myinfo";
    }
    /*
    @RequestMapping(value = "/updateInfo",method = RequestMethod.POST)
    public String updateInfo(@RequestParam("nNickname") String nNickname,
                             @RequestParam("nPassword") String nPassword,
                             @RequestParam("nAccount") String nAccount,
                             @RequestParam("nRole") String nRole,
                             HttpServletRequest request,Model model) {
        logger.info("<<<<<<<<<<   能否到达这里？？？    >>>>>>>>>>>>>>>>>>>>>>");
        String id = SSOHelper.getSSOToken(request).getId();

        User user = userService.selectByPrimaryKey(id);

        logger.info("修改信息从数据库得到的数据是<<<<<<<<  "+user);

        user.setNickname(nNickname);
        user.setPassword(nPassword);
        user.setRole(nRole);
        user.setAvatar(nAccount);

        //logger.info("<<<<<<<<<<从前台拿到的数据是      "+nNickname+nAvatar+nRole+"     >>>>>>>>>>>>>>>>>>>>>>");

        int result = userService.updateByPrimaryKey(user);
        logger.info("<<<<<<<<<<更新的结果是      "+result+"     >>>>>>>>>>>>>>>>>>>>>>");

        model.addAttribute("user",user);
        return "myinfo";

    }

    */
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public String user(HttpServletRequest request,Model model) {
        List<User> list = new ArrayList<>();
        list = userService.listAll();
        model.addAttribute("userList",list);
        return "user";
    }

    @RequestMapping(value = "/rmUser/{id}",method = RequestMethod.GET)
    public String rmUser(@PathVariable("id") String id, HttpServletRequest request) {
        userService.delete(id);
        return "redirect:/user";
    }

    @RequestMapping(value = "/regPage",method = RequestMethod.GET)
    public String registerPage() {
        return "register";
    }

    @RequestMapping(value = "/loginPage")
    public String loginPage(HttpServletRequest request){
        if(SSOHelper.getSSOToken(request)!=null){
            return "index";
        }
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        User u = userService.findByAccount(account);
        if (account == null || password == null || "".equals(account) || "".equals(password)||u!=null) {
            model.addAttribute("register","0");
            String result = JSONObject.fromObject(model).toString();
            return result;
        }

        User userInfo = new User();
        userInfo.setAccount(account);
        userInfo.setPassword(password);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String regTime = simpleDateFormat.format(new Date());
        userInfo.setRegTime(regTime);
        userInfo.setRole("普通用户");
        userService.insert(userInfo);


        Map params = new HashMap();
        params.put("account", account);
        params.put("password", password);
        Iterator itr = userService.listByParams(params).iterator();
        if (itr.hasNext()) {
            User user=(User)itr.next();
            SSOToken ssoToken=new SSOToken();
            ssoToken.setId(user.getId());
            SSOHelper.setCookie(request,response,ssoToken,true);
            model.addAttribute("register","1");
            String result = JSONObject.fromObject(model).toString();
            return result;
        } else {
            model.addAttribute("register","0");
            String result = JSONObject.fromObject(model).toString();
            return result;
        }

    }
}
